<template>
  <el-breadcrumb separator="/" class="ml-[20px]">
    <el-breadcrumb-item v-for="(item, index) in list" :key="item.path">
      <span v-if="index === list.length - 1">{{ item.meta?.title }}</span>
      <a @click="handleLink(item)" v-else>{{ item.meta?.title }}</a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup lang="ts" name="Breadcrumb">
import { compile } from "path-to-regexp"
import { useRoute, useRouter } from "vue-router"
import type { RouteLocationMatched } from "vue-router"

type PartialRouteLocationMatched = Partial<RouteLocationMatched>

const route = useRoute()
const router = useRouter()
const list = ref<PartialRouteLocationMatched[]>([])
console.log("route", route)
const getBreadcrumb = () => {
  let matchedList: PartialRouteLocationMatched[] = route.matched.filter(
    (item) => item.meta && item.meta.title
  )

  if (matchedList.length) {
    // 目前是dashboard
    if (matchedList[0]?.path !== "/dashboard") {
      matchedList = [
        { path: "/dashboard", meta: { title: "首页" } },
        ...matchedList
      ]
    }
  }

  list.value = matchedList.filter((item) => item.meta?.breadcrumb !== false)
}

const handleLink = (item: PartialRouteLocationMatched) => {
  const { path, redirect } = item
  // 重定向的时候不做额外处理
  if (redirect) {
    router.push(redirect as string)
    return
  }
  // 处理带参数的路由
  const url = compile(path!)(route.params)
  router.push(url)
}
// 这里必须立即触发，不然刷新后面包屑不会更新
watch(() => route.path, getBreadcrumb, {
  immediate: true
})
</script>

<style scoped lang="scss"></style>
